package com.natalia.file.util;

import com.natalia.file.constants.FileConstants;
import com.natalia.file.exception.FileException;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ObjectUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * @Author yang
 **/
public class FileInfo {

    private FileInfo() {

    }

    /**
     * 处理文件名称
     */
    public static String getFilename(String pathPrefix, String filename) {
        StringBuilder builder = new StringBuilder();
        if (ObjectUtils.isNotEmpty(pathPrefix)) {
            if (!pathPrefix.startsWith(File.separator)) {
                builder.append(File.separator);
            }
            builder.append(pathPrefix);
            if (!pathPrefix.endsWith(File.separator)) {
                builder.append(File.separator);
            }
        }
        return builder.append(UUID.randomUUID())
                .append(FileConstants.EXTENSION_SEPARATOR)
                .append(FilenameUtils.getExtension(filename))
                .toString();
    }

    /**
     * 当文件不存在的时候创建文件
     *
     * @param file
     * @throws IOException
     */
    public static File createFileNotExists(File file) {
        Path path = Paths.get(file.getAbsolutePath());
        try {
            if (Files.notExists(path)) {
                Files.createDirectories(path.getParent());
                Files.createFile(path);
            }
            return path.toFile();
        } catch (Exception e) {
            throw new FileException("unable to create file: " + file.getAbsolutePath(), e);
        }
    }
}
